package railRoad.io.files;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import railRoad.Route;
import railRoad.Schedule;
import railRoad.Station;

/**
 * JSON files parser
 * 
 * @see FileWriteRead
 * @author Rukin
 * 
 */
public final class JSONReader extends FileWriteRead {

	@Override
	public void read() {
		Scanner in = new Scanner(this.getIn());

		Route route = null;

		Station station = null;
		String stationName = null, tmp;
		Float altitude = null, longitude = null;
		Integer id = null, availableTicket = null, station_id = null;

		Matcher matcher;
		String line;

		while (in.hasNext()) {
			line = in.nextLine();
			line = line.replaceAll("\\s*", "");
			matcher = Pattern
					.compile(
							"\"route_id\":([0-9]*)|\"availableTicket\":([0-9]*)|\"station_id\":([0-9]*)|"
									+ "\"name\":\"([a-z]*[0-9]*)|\"altitude\":([0-9]*)|\"longitude\":([0-9]*)")
					.matcher(line);

			while (matcher.find()) {
				if ((tmp = matcher.group(1)) != null)
					id = Integer.parseInt(tmp);
				if ((tmp = matcher.group(2)) != null)
					availableTicket = Integer.parseInt(tmp);

				if (id != null && availableTicket != null) {
					route = new Route(id, availableTicket);
				}

				if ((tmp = matcher.group(3)) != null)
					station_id = Integer.parseInt(tmp);
				if ((tmp = matcher.group(4)) != null)
					stationName = tmp;
				if ((tmp = matcher.group(5)) != null)
					altitude = Float.parseFloat(tmp);
				if ((tmp = matcher.group(6)) != null)
					longitude = Float.parseFloat(tmp);

				if (station_id != null && stationName != null
						&& altitude != null && longitude != null) {
					station = new Station(station_id, stationName, altitude,
							longitude);
					route.addStation(station);
				}// if
			}// while

			if (station != null && route != null) {
				Schedule.getInstance().addRoute(route);

				id = null;
				availableTicket = null;

				station_id = null;
				stationName = null;
				altitude = null;
				longitude = null;
				station = null;
			}// if
		}// while
			// System.out.println(Schedule.getInstance().toString() );
	}// read()

	@Override
	public void write() throws Exception {
		// TODO Auto-generated method stub

	}

}
